from pylab import *
import numpy as np
import copy
import sys
from scipy.ndimage import measurements

sys.setrecursionlimit(300000)
biao = np.random.choice(22500, 22500, replace=False)

nums = np.random.choice([0, 1], size=22500, p=[1, 0])
sd = nums.reshape(150,150)#创建150x150的全零矩阵
xiabiao = []
for i in range(150):
    for j in range(150):
        xiabiao.append([i, j])

def juzhen(s):
    global a
    sd[xiabiao[s][0]][xiabiao[s][1]] = 1
    a = sd.copy()
    return a

def digui(i, j):
    if a[i][j] == 1:
        a[i][j] = se
        if i == len(a) - 1:
            digui(0, j)
        elif a[i + 1][j] == 1:
            digui(i + 1, j)
        if i == 0:
            digui(len(a) - 1, j)
        elif a[i - 1][j] == 1:
            digui(i - 1, j)
        if j == len(a[i]) - 1:
            digui(i, 0)
        elif a[i][j + 1] == 1:
            digui(i, j + 1)
        if j == 0:
            digui(i, len(a[i]) - 1)
        elif a[i][j - 1] == 1:
            digui(i, j - 1)

plt.ion()
p1 = 0.00
dd=1

for s in biao:
    juzhen(s)
    dd+=1
    #每50次循环调用一次递归函数，进行团簇分类，该语句可以提高程序的运行效率
    if dd%50==0:
        se = 2
        for i in range(len(a) - 1):
            for j in range(len(a[i] - 1)):
                if a[i][j] == 1:
                    digui(i, j)
                    se += 1


imshow(rand,origin='lower', interpolation='nearest')
colorbar()
title("Matrix")
#plt.show()


# 对不同团簇进行分别
lw,num = measurements.label(a)
imshow(lw,origin='lower',interpolation='nearest')
colorbar()
title("Labeled clusters")
#plt.show()








area = measurements.sum(rand, lw, index=arange(lw.max() + 1))
areaImg = area[lw]
im3 = imshow(areaImg, origin='lower', interpolation='nearest')
colorbar()
title("Clusters by area")
plt.show()

# 给最大的团簇标记出来并计算大小
im3 = imshow(areaImg, origin='lower', interpolation='nearest')
colorbar()
title("Clusters by area")
sliced = measurements.find_objects(areaImg == areaImg.max())
if(len(sliced) > 0):
    sliceX = sliced[0][1]
    sliceY = sliced[0][0]
    plotxlim=im3.axes.get_xlim()
    plotylim=im3.axes.get_ylim()
    plot([sliceX.start, sliceX.start, sliceX.stop, sliceX.stop, sliceX.start], \
                          [sliceY.start, sliceY.stop, sliceY.stop, sliceY.start, sliceY.start], \
                          color="red")
    xlim(plotxlim)
    ylim(plotylim)
    plt.show()